#import requests
import json
import ssl
import uuid
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import time
from pydantic import BaseModel, Field


class Parameter(BaseModel):
    cluster_id: str


class Result(BaseModel):
    r: int


def get_request_id():
    return str(uuid.uuid1())


def delete_req(cluster_id):
    # 禁用 SSL 证书验证
    ssl_context = ssl._create_unverified_context()

    url = "http://10.210.153.106:12021/cluster/deleteRayCluster"
    request_id = get_request_id()
    print(f'Delete ray cluster request id: {request_id}, cluster id: {cluster_id}')

    data = {
        "RequestId": request_id,
        "ClusterId": cluster_id,
        "KubeConfPath": "/root/.kube/config",
        "Namespace": "ray-engine",
    }

    try:
        # 将数据编码为 JSON 字节
        encoded_data = json.dumps(data).encode('utf-8')

        # 创建请求对象
        req = Request(url, data=encoded_data, method='POST')
        req.add_header('Content-Type', 'application/json')

        # 发送请求
        with urlopen(req, context=ssl_context) as response:
            response_data = response.read().decode('utf-8')
            received_data = json.loads(response_data)

            if response.status == 200:
                print("Received data:", received_data)
            else:
                print("Request returned with status code:", response.status)
                print("Response:", received_data)

    except HTTPError as e:
        print(f"HTTP Error occurred: {e.code} - {e.reason}")
        if e.code == 400:
            error_body = e.read().decode('utf-8')
            print("Error details:", error_body)
    except URLError as e:
        print(f"URL Error occurred: {e.reason}")
    except json.JSONDecodeError as e:
        print(f"Failed to decode JSON response: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


def main(param: Parameter) -> Result:
    time.sleep(120)
    delete_req(param.cluster_id)
    return Result(r=1)
